package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"fresh-box-mgr/cache"
	"fresh-box-mgr/freshrpc/freshrpc"
	"fresh-box-mgr/freshrpc/internal/svc"
	"fresh-box-mgr/model"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListFreshLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListFreshLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListFreshLogic {
	return &ListFreshLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListFreshLogic) ListFresh(in *freshrpc.ListFreshRequest) (*freshrpc.ListFreshResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("listFresh%s", in)
	var fresh []*freshrpc.ListFresh
	result, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if result == "" {
		fresh = model.ListFresh(model.DB, in)
		marshal, _ := json.Marshal(&fresh)

		cache.Rdb.Set(cache.Ctx, key, marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &fresh)
	}

	return &freshrpc.ListFreshResponse{
		List: fresh,
	}, nil
}
